<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <!-- <template #after>
          在页面的右侧内容
        </template>
        <template #before>
          在页面的左侧内容
        </template> -->
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="export2Excel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="isShowDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" prop="staffPhoto" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/img.jpeg')" :src="row.staffPhoto" alt="" class="avatar">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 作用域插槽 -->
            <template #default="obj">{{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <el-switch
                v-model="obj.row.enableState"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageSetting.size"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <add-employee :is-show-dialog="isShowDialog" />
      <AssignRole ref="assignRole" :is-show-role-dialog.sync="isShowRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import Employeenum from '@/api/constant/employees'
import { getEmployee, delEmployee } from '@/api/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import AssignRole from './components/assign-role.vue'
export default {
  // filters: {
  //   formatData(oldVal) {
  //     return oldVal.split('T')[0]
  //   }
  // },
  components: { addEmployee, AssignRole },
  data() {
    return {
      pageSetting: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      isShowDialog: false,
      isShowRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async assignRole(id) {
      await this.$refs.assignRole.getUserDetail(id)
      this.userId = id
      this.isShowRoleDialog = true
    },
    async getEmployee() {
      const { rows, total } = await getEmployee(this.pageSetting)
      this.employeeList = rows.map(user => {
        const enableState = Math.round(Math.random())
        console.log(enableState)
        return {
          ...user,
          enableState: user.enableState || enableState
        }
      })
      this.total = total
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getEmployee()
    },
    formatEmployment(row, column, cellVal) {
      // if (cellVal === 1) {
      //   return '正式工'
      // } if (cellVal === 2) {
      //   return '临时工'
      // }
      // 枚举数据
      // const hireType = [
      //   { id: 1, value: '正式' },
      //   { id: 2, value: '非正式' }
      // ]
      const obj = Employeenum.hireType.find(item => item.id === cellVal)
      return obj ? obj.value : '未知'
    },
    async export2Excel() {
      // // 获取所有数据
      // const { rows } = await getEmployee({
      //   page: 1,
      //   size: this.total
      // })
      // console.log(rows)

      // 生成 excel 文件的方法
      // 获取所有数据
      const { rows } = await getEmployee({
        page: 1,
        size: this.total
      })
      console.log(rows)

      const header = ['姓名', '工号', '聘用形式', '入职日期', '转正日期']

      // 对数据进行转换
      const data = rows.map(user => {
        return this.objToArr(user)
      })

      console.log(rows)
      console.log(data)

      export_json_to_excel({
        header,
        data
      })
    },
    objToArr(objUser) {
      const arrUser = []
      // 中间转换
      const zidian = {
        '姓名': 'username',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime'
      }

      for (const key in zidian) {
        const enKey = zidian[key]
        const value = objUser[enKey]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 时间处理
          arrUser.push(formatDate(value))
        } else if (enKey === 'formOfEmployment') {
          // 聘用形式
          const obj = Employeenum.hireType.find(item => item.id === value)
          arrUser.push(obj ? obj.value : '未知')
        } else {
          arrUser.push(value)
        }
      }
      return arrUser
    },
    async delEmployee(id) {
      // 二次确认
      await this.$confirm('确认删除')
      // 发起请求
      await delEmployee()
      // 成功提示
      this.$message.success('操作成功')
      // 更新数据
      this.getEmployee()
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 180px;
  height: 120px;
  object-fit: cover;
}
</style>
